<template>
  <div class="#app">
    <el-card>
      <!-- 2.1 顶部操作 -->

      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 使用clearable属性即可得到一个可清空的输入框   clear	在点击由 clearable 属性生成的清空按钮时触发-->
          <el-input
            placeholder="请输入用户名"
            v-model="queryInfo.query"
            class="input-with-select"
            clearable
            @clear="getList"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="getList"></el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showAddDialog">添加</el-button>
          <el-button type="primary" @click="deleteBlogs(multipleSelection)"
            >批量删除</el-button
          >
        </el-col>
      </el-row>

      <el-table
        :data="list"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <!-- 索引列 -->
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="权限" prop="userRole">
          <template slot-scope="{row}">
                {{authorityList[row.userRole-1]}}
            </template>
        </el-table-column>
        <el-table-column label="备注" prop="remarks"></el-table-column>
        <!-- <el-table-column label="创建时间" prop="createdTime"></el-table-column> -->

        <el-table-column label="创建时间" align="center" width="120px">
          <template slot-scope="{ row }">
            <span>{{ row.createdTime | dateFormat }}</span>
          </template>
        </el-table-column>
        <!-- 自定义列 -->
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="showEditDialog(scope.row.id)"
              >编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeById(scope.row.id)"
              >删除
            </el-button>
            <!-- {{scope.row}} -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 2.3 分页 -->

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
        :page-sizes="[5, 10, 20, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 3.弹框区域 -->

    <!-- 添加框 -->
    <!-- modify -->
    <el-dialog
      title="添加"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username ">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="userRole ">
          <!-- <el-input v-model="addForm.userRole"></el-input> -->
          <el-select v-model="addForm.roomType" placeholder="权限" clearable>
            <el-option
              v-for="item in authorityObjList"
              :key="item.id"
              :label="item.authority"
              :value="item.id">
            </el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password ">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="addForm.remarks"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑框 -->
    <!-- modify -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        ref="editFormRef"
        :rules="editFormRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username ">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="userRole ">
          <!-- <el-input v-model="editForm.userRole"></el-input> -->
           <el-select v-model="editForm.userRole" placeholder="权限" clearable>
            <el-option
              v-for="item in authorityObjList"
              :key="item.id"
              :label="item.authority"
              :value="item.id">
            </el-option>
           </el-select>
        </el-form-item>
        <el-form-item label="密码" prop="password ">
          <el-input v-model="editForm.password"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" v-model="editForm.remarks"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="update">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  fecthList,
  add,
  update,
  deleteOne,
  deleteByIds,
  getById,
  queryAuthorityWithList
} from "../../api/user_manage";
export default {
  data() {
    return {
      queryInfo: {
        query: "",
        pageNum: 1,
        pageCount: 10,
      },
      list: [],
      total: 0,
      addDialogVisible: false,
      adddialog: [],
      // modify
      addForm: {},
      // modify
      addFormRules: {
        username: [
          { required: true, message: "不能和为空", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        userrole: [
          { required: true, message: "商品名称", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "不能和为空", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        remarks: [
          { required: true, message: "不能和为空", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
      },
      editDialogVisible: false,
      // modify
      editForm: {},
      // modify
      editFormRules: {
        username: [
          { required: true, message: "不能和为空", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        userrole: [
          { required: true, message: "商品名称", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "不能和为空", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        remarks: [
          { required: true, message: "不能和为空", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
      },

      multipleSelection: [],
      ids: [],

      // 权限列表
      authorityList: [],
      authorityObjList: []
    };
  },
  created() {
    this.getList();
    this.getAuthorityList();
  },
  //方法
  methods: {
    //查询  async  await
    getList() {
      //{k1:v1,k2:v2}  ---> ?k1=v1&k2=v2    query=&pagenum=1&pagesize=10
      // console.log(this.queryInfo, this.$qs.stringify(this.queryInfo));
      fecthList(this.queryInfo).then((response) => {
        this.list = response.data.records;
        this.total = response.data.total;
        setTimeout(() => {}, 1.5 * 1000);
      });
    },

    // 获取权限列表
    getAuthorityList(){
      queryAuthorityWithList().then( res => {
        this.authorityObjList = res.data
        res.data.forEach(element => {
          this.authorityList.push(element.authority)
        });
        console.log("权限列表==>" + this.authorityList);
      })
    },

    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.queryInfo.pageCount = val;
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryInfo.pageNum = val; // 获取新页码
      this.getList();
    },

    //添加
    //弹框
    showAddDialog() {
      this.addDialogVisible = true;
    },

    add() {
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(valid);

        if (!valid) return;

        console.log(this.addForm);

        add(this.addForm).then((response) => {
          this.addDialogVisible = false;
          this.$notify({
            title: "成功",
            message: "添加成功",
            type: "success",
            duration: 5000,
          });
          this.getList();
        });
      });
    },

    // @close="addDialogClosed"
    addDialogClosed() {
      // console.log(this.$refs); //可以获取所有带ref属性的元素
      this.$refs.addFormRef.resetFields(); //清空表单
    },

    //更新
    showEditDialog(id) {
      getById(id).then((res) => {
        console.log(res.data);
        this.editForm = res.data; // 对象复制
        this.editDialogVisible = true;
      });

      // if (res.code !== 5000) {
      //     return this.$message.error('查询信息失败！')
      //   }
    },
    update() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        update(this.editForm).then((response) => {
          const index = this.list.findIndex((v) => v.id === this.editForm.id);
          this.list.splice(index, 1, this.editForm);
          this.$notify({
            title: "修改成功",
            type: "success",
            duration: 5000,
          });
          this.getList();
        });
        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据列表
      });
    },

    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    removeById(id) {
      this.$confirm("此操作将永久删除数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // 删除逻辑
          deleteOne(id).then(() => {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 5000,
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },
    deleteBlogs(val) {
      val.forEach((element) => {
        this.ids.push(element.id);
      });
      console.log(this.ids);

      deleteByIds(this.ids).then(() => {
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 5000,
        });
        this.ids = [];

        this.getList();
      });
    },
  },
};
</script>
<style scoped>
.el-card {
  margin-top: 15px;
}

.el-table {
  margin-top: 15px;
  margin-bottom: 15px;
}
</style>
